<template>
    <div class="commonELeLoan">
        <Col>
            <FormItem label="还款方式" prop="payMethod" >
                <Input  v-model="loanForm.payMethod"  placeholder=""  :disabled="isShowDetails||isDisabled" class="w200"/>
            </FormItem>
        </Col>
        <Col v-show="diver!='carAdd'" style="height:56px">

        </Col>
        <Col>
            <FormItem label="首付比例(%)" prop="downPayScale" >
                <Input  v-model="loanForm.downPayScale"  placeholder="" @on-change="inputPayScale('downPayScale',loanForm.downPayScale,loanFormOld.downPayScale)" :disabled="!isAppear" class="w200"/>
                    <span  :class="loanForm.downPayScale+'' !== loanFormOld.downPayScale+'' ? 'red' :''" v-show="loanForm.downPayScale+'' !== loanFormOld.downPayScale+''">
                       {{loanFormOld.downPayScale}}
                    </span>
            </FormItem>
        </Col>
        <Col>
            <FormItem label="首付金额(元)" prop="downPayAmt">
                <Input v-model="loanForm.downPayAmt"  placeholder="" @on-change="inputPayAmt('downPayAmt')" :disabled="isShowDetails||isDisabled" class="w200"/>
                <input type="hidden" :value="downPayAmt"/>
                    <span :class="loanForm.downPayAmt+'' !== loanFormOld.downPayAmt+'' ? 'red' :''" v-show="loanForm.downPayAmt+'' !== loanFormOld.downPayAmt+''">
                       {{loanFormOld.downPayAmt}}
                    </span>
            </FormItem>
        </Col>
        <Col>
            <FormItem label="贷款期限(期)" prop="loanLimit">
                <InputNumber
                :min="0"
                v-model="loanForm.loanLimit"
                :disabled="!isAppear"
                @on-blur="inputLoanLimit"
                @on-change="inputPayScale"
                style="width: 150px"></InputNumber>
                <!--<p style="display:inline-block" class="term" >
                    默认区间:<span v-for="(item,index) in term" :key="index" :class="{active:curSpan===index}" @click="selectTerm(item,index)"><i>{{item}}</i><b v-show="index!=term.length-1">~</b></span>
                </p>-->
                    <span  :class="loanForm.loanLimit+'' !== loanFormOld.loanTerm+'' ? 'red' :''" v-show="loanForm.loanLimit+'' !== loanFormOld.loanTerm+''">
                       {{loanFormOld.loanTerm}}
                    </span>
            </FormItem>
        </Col>
        <Col>
            <FormItem label="首期月供" prop="monthPayAmt">
                <Input v-model="loanForm.monthPayAmt"   placeholder="" :disabled="isShowDetails||isDisabled" class="w200"/>
                    <span :class="loanForm.monthPayAmt+'' !== loanFormOld.monthPayAmt+'' ? 'red' :''" v-show="loanForm.monthPayAmt+'' !== loanFormOld.monthPayAmt+''">
                       {{loanFormOld.monthPayAmt}}
                    </span>
            </FormItem>
        </Col>
        <Col>
            <FormItem label="贷款金额(元)" prop="loanAmt">
                <Input v-model="loanForm.loanAmt"   placeholder="" @on-change="inputLoanAmt(loanForm.loanAmt)" :disabled="!isAppear" class="w200"/>
                    <span :class="loanForm.loanAmt+'' !== loanFormOld.loanAmt+'' ? 'red' :''" v-show="loanForm.loanAmt+'' !== loanFormOld.loanAmt+''">
                       {{loanFormOld.loanAmt}}
                    </span>
                <input type="hidden" :value="loanAmt"/>
            </FormItem>
        </Col>
        <Col>
            <FormItem label="还款频率" prop="payRate" >
                <Input v-model="loanForm.payRate"  placeholder=""  :disabled="isShowDetails||isDisabled" class="w200"/>
             <!--   <tag style="width: 70px;">
                    <span  :class="loanForm.payRate + '' !== loanFormOld.payRate+'' ? 'red' :''"  >
                        {{loanFormOld.payRate}}
                    </span>
                </tag>-->
            </FormItem>
        </Col>
        <Col>
            <FormItem label="客户利率" prop="custRate">
                <Input v-model="loanForm.custRate"   placeholder="" :disabled="isShowDetails||isDisabled" class="w200"/>
               <!-- <tag  style="width: 65px;">
                    <span :class="loanForm.custRate+'' !== loanFormOld.custRate+'' ? 'red' :''" >
                       {{loanFormOld.custRate}}
                    </span>
                </tag>-->
            </FormItem>
        </Col>
        <Col>
            <FormItem label="利息金额" prop="totalInterest">
                <Input v-model="loanForm.totalInterest"   placeholder="" :disabled="isShowDetails||isDisabled" class="w200"/>
                    <!--<span :class="loanForm.totalInterest+'' !== loanFormOld.totalInterest+'' ? 'red' :''" v-show="loanForm.totalInterest+'' !== loanFormOld.totalInterest+''">
                       {{loanFormOld.totalInterest}}
                    </span>-->
            </FormItem>
        </Col>
        <Col v-show="isTail">
            <FormItem label="尾款金额(元)" prop="tailPayAmt">
                <Input v-model="loanForm.tailPayAmt"  placeholder="" @on-change="inputPayAmt('tailPayAmt')" :disabled="isShowDetails||isDisabled" class="w200"/>
                    <span :class="loanForm.tailPayAmt+'' !== loanFormOld.tailPayAmt+'' ? 'red' :''" v-show="loanForm.tailPayAmt+'' !== loanFormOld.tailPayAmt+''">
                       {{loanFormOld.tailPayAmt}}
                    </span>
            </FormItem>
        </Col>
        <Col v-show="isTail">
            <FormItem label="尾款比例(%)" prop="tailPayScale" >
                <Input v-model="loanForm.tailPayScale"  placeholder="" @on-change="inputPayScale('tailPayScale')" :disabled="isShowDetails||isDisabled" class="w200"/>
                    <span :class="loanForm.tailPayScale+'' !== loanFormOld.tailPayScale+'' ? 'red' :''" v-show="loanForm.tailPayScale+'' !== loanFormOld.tailPayScale+''">
                       {{loanFormOld.tailPayScale}}
                    </span>
            </FormItem>
        </Col>
        <Col>
            <FormItem label="贴息类型">
                <Input v-model="loanForm.discountType"   placeholder="" :disabled="isShowDetails||isDisabled" class="w200"/>
              <!--  <tag  style="width: 65px;">
                    <span :class="loanForm.discountType+'' !== loanFormOld.discountType+'' ? 'red' :''" >
                       {{loanFormOld.discountType}}
                    </span>
                </tag>-->
            </FormItem>
        </Col>
        <Col v-show="discountOption!=0">
            <FormItem  prop="discountTotalAmt">
                <span slot="label">贴息金额</span>
                <div ref="disTotalAmt" style="width: 150px;position:relative;">
                    <div class="arrow_icon">
                        <Input v-model="loanForm.discountTotalAmt"   placeholder="" :disabled="isShowDetails||isDisabled" class="w200"/>
                        <span style="left: 133px;">
                            <img src="../../../../../../../assets/images/down.png" alt="" v-if="!isShowDiscountAmt">
                            <img src="../../../../../../../assets/images/up.png" alt="" v-else>
                        </span>
                    </div>
                    <div v-if="isShowDiscountAmt" class="amt_total">
                        <div v-for="(item,index) in loanForm.loadList" style="margin-bottom: 8px;">
                            <div class="amt_list_type">
                                <FormItem :label="item.discountParty" :label-width="60" class="itemLable">
                                    <Input
                                    v-model="item.discountAmt"
                                    style="width:50%;"
                                    placeholder=""
                                    :readonly="item.isreadonly"
                                     :disabled="isShowDetails||isDisabled"/>
                                </FormItem>
                            </div>
                        </div>
                    </div>
                </div>
            </FormItem>
        </Col>
        <Col v-show="discountOption!=0">
            <FormItem label="厂商最高贴息额" prop="maxDisCountAmt">
                <Input v-model="loanForm.maxDisCountAmt"   placeholder="" :disabled="isShowDetails||isDisabled" class="w200"/>
            </FormItem>
        </Col>
    </div>
</template>
<script>
    import * as utils from '_p/afs-apply/assets/js/utils.js'
    import vueEvent from "_p/afs-apply/assets/js/vueEvent.js"
    import {deepClone} from "@/libs/utils/ObjectClone";
    import {
        getByTypes
    }   from "_p/basic/api/admin/datadic.js";
    import {
        queryProductDetails,
        getProductRate
    } from "_p/afs-apply/api/apply-report/personal/financialProducts.js"
    export default {
        name:"commonELeLoan",
        data(){
            let validateTerm=(rule,value,callback)=>{
                if(value||value=="0"){
                if(value>=this.term[0]&&value<=this.term[1]){
                        callback();
                }else{
                    callback(new Error("请输入"+(this.term[0]||"")+"~"+(this.term[1]||"")+"期数"))
                }
                }
            }
            let valiateDownPayScale=(rule,value,callback)=>{
                if(value){
                    if(value>100||value<this.downPayRatioMin){
                        callback(new Error('请输入'+this.downPayRatioMin+'~100的首付比例'))
                        return;
                    }
                    if(this.theoryDownPayScale){
                        if(value<this.theoryDownPayScale){
                            callback('首付比例需>=理论比例'+(this.theoryDownPayScale))
                            return;
                        }
                    }
                }
                callback();
            }

            return {
                theoryDownPayScale:"",
                tempCarLoan:"",
                curSpan:"",
                isSure:false,
                validateTerm:validateTerm,
                valiateDownPayScale:valiateDownPayScale,
                downPayRatioMin:"",
                term:[
                ],
                isShowDiscountAmt:false,
            }
        },
        props:{
            //留痕
            loanFormOld:{
                type:Object,
                default:function() {
                    return {}
                }
            },
            loanForm:{
                type:Object,
            },
            isAppear: {
                type: Boolean
            },
            isShowDetails:{
                type:Boolean
            },
            loanFormValiate:{
                type:Object
            },
            selectProdInfo:{
                type:Object
            },
            queryProdInfo:{
                type:Object
            },
            isTail:{
                type:Boolean
            },
            uuid:{
                type:String
            },
            applyNo:{
                type:String
            },
            prodId:{
                type:String,
            },
            isDisabled:{
                type:Boolean
            },
            discountOption:{
                type:String
            },
            diver:{
               type:String
            },
            // totalInfoData:{
            //     type:Object
            // },
            monthPay:{
                type:Number
            },
            discount:{
                type:Number
            },
            interest:{
                type:Number
            }

        },
        computed:{
            loanAmt:function(){
                let remainAmt=0;
                if(this.diver=="car"){
                    remainAmt=utils.sub(this.loanForm.carPrice,this.loanForm.downPayAmt);
                }else if(this.diver=="additional"){
                    remainAmt=utils.sub(this.loanForm.additionalTotalAmt,this.loanForm.downPayAmt);
                }else if(this.diver=="carAdd"){
                    let price=utils.add(this.loanForm.carPrice,this.loanForm.additionalTotalAmt)
                    remainAmt=utils.sub(price,this.loanForm.downPayAmt);
                }
                if(remainAmt.toString()=="0"){
                    this.loanForm.loanAmt='';
                }else{
                    this.loanForm.loanAmt=remainAmt.toString();
                }
                if(this.$refs.loanForm&&this.loanForm.loanAmt){
                    let _this=this;
                    this.$nextTick(()=>{
                        _this.$emit('validateSingle',"loanAmt");
                    })
                }
                return remainAmt;
            },
            downPayAmt:function(){
                let payAmt=this.loanForm.downPayAmt;
                return payAmt
            },

        },
        watch:{
            monthPay(val){
                if(val){
                    this.loanForm.monthPayAmt=val;
                }
            },
            discount(val){
                if(val){
                    this.loanForm.discountTotalAmt=val;
                }
            },
            interest(val){
                if(val){
                    this.loanForm.totalInterest=val;
                }
            },
            // 'totalInfoData.totalInterest':{
            //     handler: function(val) {
            //         this.loanForm.totalInterest=val;
            //     },
            //     immediate: true,
            // },
            selectProdInfo(val){
                if(Object.keys(val).length>0){
                    let tempPeriod=[];
                    tempPeriod[0]=val.detailInfo.loanPeriodMin;
                    tempPeriod[1]=val.detailInfo.loanPeriodMax;
                    this.term=tempPeriod;
                    this.loanFormValiate['downPayScale'].push({
                        validator: this.valiateDownPayScale,trigger:'blur'
                    })
                    this.downPayRatioMin=val.detailInfo.downPayRatioMin;
                    this.initDatadic().then(dataDic=>{
                        this.loanForm.payMethod=utils.setDataDictVal(dataDic.repaymentMethod,val.detailInfo.repaymentType);
                        // this.loanForm.payRate=utils.setDataDictVal(dataDic.repaymentFrequency,val.detailInfo.repaymentFrequency);
                        //还款频率固定月付
                        this.loanForm.payRate=utils.setDataDictVal(dataDic.repaymentFrequency,"0");
                        this.loanForm.discountType=utils.setDataDictVal(dataDic.discountCategory,val.discountOption)
                    })
                }
            },
            queryProdInfo(val){
                if(Object.keys(val).length>0){
                    //input的必输类型为string
                    this.loanForm.loanLimit=val.costInfo.loanTerm;
                    this.loanForm.downPayScale=val.costInfo.downPayScale.toString();
                    this.loanForm.downPayAmt=val.costInfo.downPayAmt;
                    if(val.isTail=="1"){
                        this.loanForm.tailPayScale=val.costInfo.tailPayScale;
                        this.loanForm.tailPayAmt=val.costInfo.tailPayAmt;
                    }
                    this.loanForm.loanAmt=val.costInfo.loanAmt.toString();
                    this.tempCarLoan=val.costInfo.loanAmt;
                    this.loanForm.monthPayAmt=val.costInfo.monthPayAmt;
                    this.loanForm.custRate=val.costInfo.custRate;
                    this.loanForm.settleRate=val.costInfo.settleRate;
                    this.loanForm.totalInterest=val.costInfo.totalInterest;
                    let tempArr=[];
                    if(this.discountOption!="0"){
                        if(val.discountList&&val.discountList.length>0){
                            val.discountList.forEach((item,index)=>{
                                let tempObj={
                                    discountParty:item.discountParty,
                                    discountAmt:item.discountAmt,
                                    discountId:item.discountId,
                                }
                                tempArr.push(tempObj);
                            })
                            this.loanForm.loadList=tempArr;

                        }
                        this.loanForm.discountTotalAmt=val.costInfo.discountAmt;
                        this.loanForm.maxDisCountAmt=val.costInfo.maxDiscountAmt;
                    }
                }
            },
        },
        created(){
           this.initVailate();
        },
        mounted(){
            let _this=this;
            document.getElementById('main').addEventListener('click',(e)=>{
                if(_this.$refs.disTotalAmt){
                    if(_this.$refs.disTotalAmt.contains(e.target)){
                        _this.isShowDiscountAmt=true;
                    }else{
                        _this.isShowDiscountAmt=false;
                    }
                }
            })
        },
        methods:{
            async initDatadic(){
                //数据字典
                let arr = ["discountCategory","repaymentMethod","repaymentFrequency"];
                return await getByTypes(arr).then(res => {
                    if (res.code === "0000") {
                        return res.data;
                    }
                });
            },
            initVailate(){
                this.loanFormValiate['loanLimit']=[
                    {required: true, message:"贷款期限不能为空", trigger: "blur",type:"number"},
                    {validator:this.validateTerm,trigger: "blur",type:"number"}
                ]
                this.loanFormValiate['downPayScale']=[
                    {required: true, message: "首付比例不能为空", trigger: "blur"},
                    {validator:(rule,value,callback)=>{utils.isTwoDicmalValiate(rule,value,callback)},trigger:"blur"}
                ]
                this.loanFormValiate['loanAmt']=[
                    {required: true, message: "贷款金额不能为空", trigger: "blur"},
                    {validator:(rule,value,callback)=>{utils.isTwoDicmalValiate(rule,value,callback)},trigger:"blur"}
                ]

            },
            selectTerm(item,index){
                // 当为新增或编辑的时候
                if(!this.isShowDetails){
                    this.curSpan=index;
                    this.loanForm.loanLimit=parseFloat(item);
                    this.$emit('validateSingle',"loanLimit");
                    this.matchRate(item);
                }
            },
            inputLoanLimit(){
                let loanLimit=parseFloat(this.loanForm.loanLimit)
                this.matchRate(loanLimit)
            },
            // 匹配rate值
            matchRate(loanLimit){
                let obj={
                    applyNo:this.applyNo,
                    id:this.prodId,
                    loanTerm :loanLimit,
                    costType:"01",
                }
                getProductRate(obj,"case").then(res=>{
                    if(res.code=="0000"){
                        if(res.data){
                            this.loanForm.custRate=res.data.main.custRate;
                            this.loanForm.clearRate=res.data.main.clearRate;
                        }
                    }
                })
            },
            isDeal() {
                if (this.loanForm.downPayScale < this.loanFormOld.downPayScale) {
                    this.isSure = true
                }else{
                    this.isSure = false
                }
                this.$emit('isChange',this.isSure);
            },
            // 输入比例
            inputPayScale(type,val,valOld){
                if (val < valOld) {
                    this.isSure = true
                }else{
                    this.isSure = false
                }
                this.$emit('isChange',this.isSure);
                if(utils.isTwoDicmal(this.loanForm[type])){
                    let formprice='';
                    if(this.diver=="car"){
                        formprice=this.loanForm.carPrice;
                    }else if(this.diver=="additional"){
                        formprice=this.loanForm.additionalTotalAmt
                    }else if(this.diver=="carAdd"){
                        if(this.loanForm.carPrice||this.loanForm.additionalTotalAmt){
                            formprice=utils.add(this.loanForm.carPrice,this.loanForm.additionalTotalAmt)
                        }
                    }
                    if(formprice){
                        let price=formprice;
                        let payScale=this.loanForm[type];
                        let tempScale=utils.divided(payScale,100)
                        let multiplyAmt=utils.multiply(price,tempScale);
                         // 四舍五入
                        let payAmt=Math.round(multiplyAmt*100)/100;
                        if(type=="downPayScale"){
                            this.loanForm.downPayAmt=payAmt.toString();
                        }else if(type=="tailPayScale"){
                            this.loanForm.tailPayAmt=payAmt.toString();
                        }
                    }
                }
                if(type=='downPayScale'){
                    this.$emit('validateSingle',"downPayAmt");
                }else if(type=="tailPayScale"){
                    this.$emit('validateSingle',"tailPayAmt")
                }
            },
             // 输入金额
            inputPayAmt(type,operFlag){
                if(utils.isTwoDicmal(this.loanForm[type])){
                    let formprice='';
                    if(this.diver=="car"){
                        formprice=this.loanForm.carPrice;
                    }else if(this.diver=="additional"){
                        formprice=this.loanForm.additionalTotalAmt
                    }if(this.diver=="carAdd"){
                        if(this.loanForm.carPrice||this.loanForm.additionalTotalAmt){
                            formprice=utils.add(this.loanForm.carPrice,this.loanForm.additionalTotalAmt)
                        }
                    }
                    if(formprice){
                        let price=formprice;
                        let payAmt=this.loanForm[type];
                        let tempScale=utils.divided(payAmt,price);
                        let multiplyScale=utils.multiply(tempScale,100);
                        // 四舍五入
                        let payScale=Math.round(multiplyScale*100)/100;
                        if(type=="downPayAmt"){
                            this.loanForm.downPayScale=payScale.toString();
                            if(operFlag=='theory'){
                                this.theoryDownPayScale=this.loanForm.downPayScale
                            }
                        }else if(type=="tailPayAmt"){
                            this.loanForm.tailPayScale=payScale.toString();
                        }
                    }
                }
                if(type=='downPayAmt'){
                    this.$emit('validateSingle',"downPayScale");
                }else if(type=="tailPayAmt"){
                    this.$emit('validateSingle',"tailPayScale");
                }
            },
            // 输入贷款金额
            inputLoanAmt(loanAmt,operFlag){
                if(this.diver=="car"){
                    this.loanForm.downPayAmt=utils.sub(this.loanForm.carPrice,loanAmt).toString();
                }else if(this.diver=="additional"){
                    this.loanForm.downPayAmt=utils.sub(this.loanForm.additionalTotalAmt,loanAmt).toString();
                }else if(this.diver=="carAdd"){
                    let price=utils.add(this.loanForm.carPrice,this.loanForm.additionalTotalAmt);
                    this.loanForm.downPayAmt=utils.sub(price,loanAmt).toString();
                }
                this.inputPayAmt('downPayAmt',operFlag);
            },
        }
    }
</script>
<style>
    .hideSelectContent .ivu-select-dropdown{
        display:none;
    }
    .hideSelectContent .ivu-input{
        margin-top: 4px;
    }
    .amt_list_type .ivu-form-item-label{
        text-align:left;
    }
    .decorateProd label .ivu-checkbox{
        margin-right: 10px;
    }
    .additionalTotalAmt .ivu-form-item-error-tip{
        padding-top: 0px;
    }
    .additionalTotalAmt .itemLable .ivu-form-item-label::before,
    .additionalTotalAmt .itemChildLable .ivu-form-item-label::before{
        content: "";
    }
    .additionalTotalAmt .itemLable  .ivu-input,
    .additionalTotalAmt .itemChildLable  .ivu-input{
        border: 1px solid #dcdee2
    }
    .additionalTotalAmt .itemLable  .ivu-input:focus,
    .additionalTotalAmt .itemChildLable  .ivu-input:focus{
        box-shadow: none;
    }
    .additionalTotalAmt .itemLable.ivu-form-item-error .ivu-input,
    .additionalTotalAmt .itemChildLable.ivu-form-item-error .ivu-input{
        border:1px solid #ed4014
    }
    .additionalTotalAmt .itemLable.ivu-form-item-error .ivu-input:focus,
    .additionalTotalAmt .itemChildLable.ivu-form-item-error .ivu-input:focus{
        box-shadow:0 0 0 2px rgba(237, 64, 20, 0.2)
    }
</style>
<style scoped>
    .red{
        color: red;
    }
.commonELeLoan .ivu-col{
    width: 33.3%;
    float: left;
}
.term span>i{
    font-style: normal;
    height: 20px;
    width: 20px;
    display: inline-block;
}
.arrow_icon>span{
    position: absolute;
    cursor: pointer;
    line-height: 0px;
    top: 50%;
    transform: translateY(-50%);
}
.amt_total{
    border: 1px solid rgb(235,236,240);
    background: white;
    position: absolute;
    z-index: 99;
    width: 100%;
    padding: 10px;
}
</style>
